class UsersController < ApplicationController
  layout "main"
  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem
  
  # say something nice, you goof!  something sweet.
  #  def index
  #    redirect_to(:action => 'login') unless logged_in? || User.count > 0
  #  end
  def index
    unless logged_in?
        redirect_to(:action => 'login')
    else
      @body_id = "myhome"
      @user = User.find(self.current_user.id)
      @comments = Comment.paginate :page => params[:page], :per_page => 5, :conditions => ["user_id = ?", self.current_user.id]
      session[:original_uri] = request.request_uri
    end
  end

  def login
    @body_id = "login"
    @user = User.new(params[:user])
    return unless request.post?
    self.current_user = User.authenticate(params[:user][:login], params[:user][:password])
    if logged_in?
      if params[:remember_me] == "1"
        self.current_user.remember_me
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      redirect_back_or_default(:controller => '/main', :action => 'welcome')
    else
      flash[:notice] = "用户名或密码错误，请重新输入。"
      render :action => "login"
    end
  end

  def reg
    @body_id = "reg"
    @user = User.new(params[:user])
    return unless request.post?
    @user.save!
    # self.current_user = @user
    self.current_user = User.authenticate(params[:user][:login], params[:user][:password])
    redirect_back_or_default(:controller => '/users', :action => 'succeed')
  rescue ActiveRecord::RecordInvalid
    render :action => 'reg'
  end
  
  def show
    @body_id ="myhome"
    @user = User.find(params[:id])
    @comments = Comment.paginate :page => params[:page], :per_page => 5, :conditions => ["user_id = ?", params[:id]]
  end
  
  def edit
    @body_id ="myhome"
    @user = User.find(self.current_user.id)
  end
  
  def update
    @body_id ="myhome"
    @user = User.find(self.current_user.id)
    unless request.get?
      if @user.update_attributes(params[:user])
        flash[:notice] = '密码修改成功。'
        redirect_to :action => 'edit'
      else
        render :action => 'edit'
      end
    else
      redirect_to :action => 'edit'
    end
  end
  
  def succeed
    @body_id ="reg"
  end
  
  def logout
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "退出登录状态。"
    redirect_back_or_default(:controller => '/main', :action => 'index')
  end
  
  def upface
    @body_id = "reg"
    @face = Face.new(params[:face])
    @face.user_id = current_user.id
    return unless request.post?
    @face.save!
    redirect_to :action => 'index'
  rescue ActiveRecord::RecordInvalid
    render :action => 'upface'
  end

end
